﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HomeServer
{
    public partial class Form1 : Form
    {
        TcpListener tcplistener;
        TcpClient tcpClient;

        public Form1()
        {
            InitializeComponent();
        }

        private void btn_Listen_Click(object sender, EventArgs e)
        {
            try
            {
                tcplistener = NetHelper.CreateTcpListener(System.Net.IPAddress.Any, int.Parse(this.txt_Listen.Text.Trim()));
                tcplistener.Start(10);

             
                ThreadPool.QueueUserWorkItem((o) => {

                    tcpClient = tcplistener.AcceptTcpClient();
                    while (tcpClient.Connected)
                    {

                        using (var stream = tcpClient.GetStream())
                        {
                            List<byte> li = new List<byte>();
                            int tmp = -1;
                            while ((tmp = stream.ReadByte()) != -1)
                            {
                                li.Add((byte)tmp);
                            }

       
                            var str = Encoding.UTF8.GetString(li.ToArray());
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btn_Send_Click(object sender, EventArgs e)
        {
            try
            {
                using (var stream = tcpClient.GetStream())
                {
                    var by=Encoding.UTF8.GetBytes(this.txt_Send.Text.Trim());
                    stream.Write(by, 0, by.Length);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
